const router = require('koa-router')()

const axios = require("axios");
var cheerio = require("cheerio");

var models = require('../models');



router.get('/', async (ctx, next) => {

  // const admin = await models.User.create({ userName: "admin",password:"123456" });
  // console.log('admin 已保存到数据库!');
  // await admin.reload();
  // console.log(admin.toJSON()); 
  // http://wufazhuce.com/
  let headers={
    accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    acceptEncoding: "gzip, deflate",
    acceptLanguage: "zh-CN,zh;q=0.9,en;q=0.8",
    userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36",
  }
  axios
  .get("http://wufazhuce.com/", { headers })
  .then(function (res) {
    let text = unescape(res.data.replace(/\\u/g, "%u")); //将unicode码转换成中文
    let $ = cheerio.load(text, {
      decodeEntities: false,
    });
    console.log("首页推荐" + "in " + new Date().toString());
    // $(".fp-one-cita a").each(function () {
    //   let text = $(this).html();
    //   console.log(text);
    // });
    // $(".fp-one-titulo-pubdate").each(function () {
    //   let text = $(this).html();
    //   console.log(text);
    // });
    $(".carousel-inner .item").each(function () {
      let dom = $('.fp-one-titulo-pubdate .dom',this).text();
      let may = $('.fp-one-titulo-pubdate .may',this).text();
      let text = $('.fp-one-cita a',this).text();
      console.log(may, dom, text);
    });

  })
  .catch(function (err) {
    console.log("failed", err);
  });



  await ctx.render('index',  { 
    title: '自娱自乐',
    user: {
      name: 'Index',
      tags: ['art', 'template', 'nodejs']
    }
  })

})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
